﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace FSM_Framework
{
    public partial class MainWindiwoViewModel : ObservableObject
    {
        IBladeDeviceSystem _bladeDeviceSystem;


        public MainWindiwoViewModel()
        {
            _bladeDeviceSystem = new BladeDeviceSystem();

            _bladeDeviceSystem.StateChanged -= bladeDeviceSystem_StateChanged;
            _bladeDeviceSystem.StateChanged += bladeDeviceSystem_StateChanged;
            _bladeDeviceSystem.IsBusyChanged -= _bladeDeviceSystem_IsBusyChanged;
            _bladeDeviceSystem.IsBusyChanged += _bladeDeviceSystem_IsBusyChanged;
            Message = $"当前状态: {_bladeDeviceSystem.BladeState}";

        }

        [ObservableProperty]
        private string _message;
        [ObservableProperty]
        private bool _isOperationEnabled = false;
        private void _bladeDeviceSystem_IsBusyChanged(object? sender, bool e)
        {
            IsOperationEnabled = e == false;
            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                StartCommand.NotifyCanExecuteChanged();
            }));
        }

        [RelayCommand(CanExecute = nameof(CanStart))]
        private void Start()
        {
            _bladeDeviceSystem.Start();
        }
        private bool CanStart()
        {
            return _bladeDeviceSystem.CanExecuteStarting();
        }

        [RelayCommand]
        private void Stop()
        {
            _bladeDeviceSystem.Stop();
        }


        private void bladeDeviceSystem_StateChanged(object? sender, StateMachine.StateChangedArgs<BladeState> e)
        {
            Message = $"之前状态: {e.StateBefore}-当前状态: {e.State}";
            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                StartCommand.NotifyCanExecuteChanged();
            }));

        }
    }
}
